<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #resourceAttributeSlot="{ model, field }">
        <JDictSelectTag  :value="model[field]" dictCode="resource_attribute" :showChooseOption="false" @change="handleDeptSuccess($event, model)"/>
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="调拨入库明细" key="busMiscellaneousStorageItem" :forceRender="true">
        <JVxeTable keep-source resizable ref="busMiscellaneousStorageItem"
          :loading="busMiscellaneousStorageItemTable.loading" :columns="busMiscellaneousStorageItemTable.columns"
          :dataSource="busMiscellaneousStorageItemTable.dataSource" :height="340" :rowNumber="true" :rowSelection="true"
          :disabled="formDisabled" :toolbar="true">
          <template #associationCodeSlot="props">
            <a-input-search @search="handleAssociationCodeView(props)" placeholder="请选择设备"
              v-model:value="props.row.associationName"></a-input-search>
          </template>
          <template #unitSlot="props">
            <a-input-search @search="handleUnitView(props)" placeholder="请选择单位"
              v-model:value="props.row.unitName"></a-input-search>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>

  <!-- 工作中心 -->
  <workCenterListSelectModel @register="workCenterModal" @getSelectResult="workCenterHandleSuccess" v-bind="getBindValue"></workCenterListSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, watch } from 'vue';
import { Modal } from 'ant-design-vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods';
import { formSchema, busMiscellaneousStorageItemColumns } from '../resourceDefinition.data';
import { saveOrUpdate, busMiscellaneousStorageItemList } from '../resourceDefinition.api';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { useDeptStore } from '/@/store/modules/dept';
import workCenterListSelectModel from '/@/views/components/workCenterListSelectModel.vue';

const deptStore = useDeptStore();

const getBindValue = Object.assign({}, '');

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const formDisabled = ref(false);
const refKeys = ref(['busMiscellaneousStorageItem']);
const activeKey = ref('busMiscellaneousStorageItem');
const busMiscellaneousStorageItem = ref();
const tableRefs = { busMiscellaneousStorageItem };
const busMiscellaneousStorageItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: busMiscellaneousStorageItemColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(busMiscellaneousStorageItemList, { id: data?.record?.id }, busMiscellaneousStorageItemTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'busMiscellaneousStorageItem';
  busMiscellaneousStorageItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    basPreProcessResourceDefinitionItemList: allValues.tablesValue[0].tableData,
  };
}

const deptName = computed(() => deptStore?.getDeptName);
//表单提交事件
async function requestAddOrEdit(values) {
  const data = {
    ...values,
    belongDepartmentName: deptName.value
  }
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(data, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}


const [workCenterModal, { openModal: openWorkCenterModal }] = useModal();

let index: number | null = null;
//打开选择设备
function handleAssociationCodeView(props) {
  openWorkCenterModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

const modelData = reactive({
  resourceAttribute: null,
});

//工作中心回写
function workCenterHandleSuccess(val, values) {
  if (Number(modelData.resourceAttribute) === 1) {

  } else {
    setFieldsValue({
      associationCode: val[0].item.workCenterCode,
      associationName: val[0].item.workCenterName,
  });
  }
}

// 已选择了属性，再次修改，提示
watch(() => modelData.resourceAttribute, (_newVal, oldVal) => {
  if (!!oldVal) {
    Modal.confirm({
    title: '提示',
    content: '修改资源属性，会清空明细列表，是否确定?',
    onOk() {
      busMiscellaneousStorageItemTable.dataSource = [];
    },
    onCancel() {
      console.log('Cancel');
    },
  });
  }
})
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>
